//
//  EJSSearchViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/21.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSSearchViewController.h"
#import "FlyCollectionViewAlignFlowLayout.h"
#import "EJSSearchHeaderReusableView.h"
#import "EJSGoodsListViewController.h"

#import "EJSSearchHeaderReusableView.h"
#import "EJSSearchWordCCell.h"

#import "EJSSearchHistoryRequest.h"
#import "EJSHotSearchRequest.h"

@interface EJSSearchTitleView:UIView

@property (strong, nonatomic) UITextField *textField;
@property (strong, nonatomic) UIButton *cancelButton;

@end

@implementation EJSSearchTitleView

- (id)init{
    return [self initWithFrame:CGRectZero];
}


- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        [self addOwnViews];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        [self addOwnViews];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    _textField.size = CGSizeMake(self.width - 75, 30);
    _textField.left = 12;
    _textField.top = self.height/2 - _textField.height/2;
    
    self.cancelButton.left = _textField.right;
    self.cancelButton.top = 0;
    self.cancelButton.width = self.width - _textField.right;
    self.cancelButton.height = self.height;
}
- (void)setFrame:(CGRect)frame {
    
    [super setFrame:CGRectMake(0, 0, self.superview.frame.size.width, self.superview.bounds.size.height)];
}

- (void)addOwnViews{
    self.translatesAutoresizingMaskIntoConstraints = NO;
    
    _textField = [[UITextField alloc] init];
    _textField.font =  [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    _textField.textColor = UIColorFromRGB(0x3C4151);
    _textField.borderStyle = UITextBorderStyleNone;
    _textField.cornerRadius = 15;
    _textField.returnKeyType = UIReturnKeySearch;
    _textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索商品名称／类别" attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x3C4151)}];
    _textField.backgroundColor = UIColorFromRGB(0xF6F6F6);
    [self addSubview:_textField];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 43, 30);
    button.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [button setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    _textField.leftViewMode = UITextFieldViewModeAlways;
    _textField.leftView = button;
    
   button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button sizeToFit];
    [button.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button setTitleColor:UIColorFromRGB(0xA4A4A4) forState:UIControlStateNormal];
    [self addSubview:button];
    self.cancelButton = button;
}


@end

@interface EJSSearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) NSArray *searchHistory;//本地搜索记录
@property (strong, nonatomic) NSArray *hotSearchHistory;//热门搜索

@end

@implementation EJSSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getSearchHistory];
    [self getHotSearchHistory];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getSearchHistory];
}

- (void)configOwnViews{
    [self configNavigationLeftItemWithImage:[UIImage imageNamed:@"back_icon"]];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 50, 50)];
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:titleView.bounds];
    searchBar.placeholder = @"搜索商品名称／类别";
    searchBar.searchBarStyle = UISearchBarStyleDefault;
    searchBar.delegate = self;
    [titleView addSubview:searchBar];
    self.navigationItem.titleView = titleView;

    FlyCollectionViewAlignFlowLayout *layout = [[FlyCollectionViewAlignFlowLayout alloc] initLayoutWithCollectionViewAlignType:FlyCollectionViewAlignLeft];
    layout.sectionInset = UIEdgeInsetsMake(0, 12, 21, 12);
    layout.minimumLineSpacing = 12;
    layout.minimumInteritemSpacing = 12;
    [self.collectionView setCollectionViewLayout:layout];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSSearchWordCCell" bundle:nil] forCellWithReuseIdentifier:@"EJSSearchWordCCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSSearchHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EJSSearchHeaderReusableView"];
}

- (void)rightBarButtonAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Request
- (void)getSearchHistory{
    self.searchHistory = [EJSSearchHistoryRequest getSearchHistory];
    [self.collectionView reloadData];
}

- (void)getHotSearchHistory{
    FlyWeakSelf
    [[EJSHotSearchRequest new] asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.hotSearchHistory = response.data;
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        
    }];
}
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if(textField.text){
        [self searchKeyWord:textField.text];
    }
    return YES;
}

#pragma mark - UI-CollectionViewDataSource|Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section == 0){
        if(self.searchHistory.count > 0){
            return self.searchHistory.count;
        }
        return 1;
    }else if (section == 1){
        if(self.hotSearchHistory.count > 0){
            return self.hotSearchHistory.count;
        }
        return 1;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    EJSSearchWordCCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSSearchWordCCell" forIndexPath:indexPath];
    EJSSearchHistoryModel *model = nil;
    if(indexPath.section == 0){
        if(self.searchHistory.count > 0){
            model = self.searchHistory[indexPath.item];
        }
        
    }else if (indexPath.section == 1){
        if(self.hotSearchHistory.count > 0){
            model = self.hotSearchHistory[indexPath.item];
        }
    }
    if(model){
        ccell.textLabel.backgroundColor = UIColorFromRGB(0xF6F6F6);
        ccell.textLabel.text = model.content;
    }else{
        ccell.textLabel.text = @"暂无搜索历史";
        ccell.textLabel.backgroundColor = kClearColor;
    }
    return ccell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    EJSSearchHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSSearchHeaderReusableView" forIndexPath:indexPath];
    headerView.clearButton.hidden = YES;
    if(indexPath.section == 0){
        headerView.titleLabel.text = @"历史记录";
        if(self.searchHistory.count > 0){
            headerView.clearButton.hidden = NO;
            [headerView.clearButton addTarget:self action:@selector(cleanSearchHistory) forControlEvents:UIControlEventTouchUpInside];
        }
    }else{
        headerView.titleLabel.text = @"热门搜索";
    }
    return headerView;
}

- (void)cleanSearchHistory{
    [EJSSearchHistoryRequest cleanSearchHistory];
    [self getSearchHistory];
}

#pragma mark - UICollectionDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSSearchHistoryModel *model = nil;
    CGFloat width = ScreenWidth;
    if(indexPath.section == 0){
        if(self.searchHistory.count > 0){
            model = self.searchHistory[indexPath.item];
        }
        
    }else if (indexPath.section == 1){
        if(self.hotSearchHistory.count > 0){
            model = self.hotSearchHistory[indexPath.item];
        }
    }
    if(model){
        CGSize size = [model.content sizeWithFont:kSystemFontSize(13) maxSize:CGSizeMake(ScreenWidth, ScreenHeight)];
        width = size.width + 24;
    }
    return CGSizeMake(width, 25);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(ScreenWidth, 55);
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSSearchHistoryModel *model = nil;
    if(indexPath.section == 0){
        if(self.searchHistory.count > 0){
            model = self.searchHistory[indexPath.item];
        }
        
    }else if (indexPath.section == 1){
        if(self.hotSearchHistory.count > 0){
            model = self.hotSearchHistory[indexPath.item];
        }
    }
    if(model){
        [self searchKeyWord:model.content];
    }
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:NO];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self searchKeyWord:searchBar.text];
}


#pragma mark - Search KeyWord
- (void)searchKeyWord:(NSString *)keyWord{
    [EJSSearchHistoryRequest setSearchHistory:keyWord];
    EJSGoodsListViewController *goodsListVC = [[EJSGoodsListViewController alloc] initWithNibName:@"EJSGoodsListViewController" bundle:nil];
    goodsListVC.keyWord = keyWord;
    goodsListVC.shopId = self.shopId;
    [self.navigationController pushViewController:goodsListVC animated:NO];
}


@end
